package com.gsc.filter;

import com.alibaba.fastjson.JSON;
import com.gsc.constants.SystemConstants;
import com.gsc.domain.ResponseResult;
import com.gsc.domain.entity.LoginUser;
import com.gsc.enums.AppHttpCodeEnum;
import com.gsc.utils.JwtUtil;
import com.gsc.utils.RedisCache;
import com.gsc.utils.WebUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author gscstart
 * @create 2023/2/7-11:08
 *
 * 做登录后请求校验的过滤器
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        //获取请求头中的token
        String token = request.getHeader(SystemConstants.TOKEN);
        //如果没有token，请求放行，去交给security处理
        if(!StringUtils.hasText(token)){
            //说明接口不需要登录，直接放行
            filterChain.doFilter(request,response);
            return ;
        }

        Claims claims = null;
        try {
            //解析token
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            //token超时  token非法
            //响应告诉前端需要重新登录
            ResponseResult errorResult = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            //如果出现错误，使用web工具类响应给前端JSON格式的信息
            WebUtils.renderString(response, JSON.toJSONString(errorResult));
            return ;
        }
        //获取userid
        String userId = claims.getSubject();
        //从redis中获取用户信息
        LoginUser loginUser = redisCache.getCacheObject(SystemConstants.BOLG_KEY + userId);
        //如果从redis获取不到，
        if(Objects.isNull(loginUser)){
            //说明登录过期  提示重新登录
            ResponseResult errorResult = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            WebUtils.renderString(response, JSON.toJSONString(errorResult));
            return ;
        }

        //存入SecurityContextHolder
            //UsernamePasswordAuthenticationToken 认证过
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //走到这  是登录的状态，token也合法，就放行
        filterChain.doFilter(request,response);
    }
}
